import tkinter as tk
from tkinter import messagebox
import sys
import os

# 添加正确的路径
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.join(current_dir, '..', '..', '..')
if project_root not in sys.path:
    sys.path.insert(0, project_root)

from src.core.item_manager import create_item, delete_item, get_items_count, can_add_more_items
from src.storage.file_manager import save_to_file, load_from_file, backup_data
from src.ui.tkinter.screens.launch_screen import show_launch_screen
from src.ui.tkinter.screens.selection_screen import show_selection_screen
from src.ui.tkinter.screens.creation_screen import show_creation_screen
from src.ui.tkinter.screens.detail_screen import show_detail_screen
from src.ui.tkinter.styles.colors import BACKGROUNDS

class MainWindow:
    def __init__(self, root):
        self.root = root
        self.items = []
        self.current_screen = None
        self.screen_history = []
        
        self.setup_window()
        self.load_data()
        self.show_launch_screen()
    
    def setup_window(self):
        self.root.title("🎮 游戏角色收藏管理器")
        self.root.geometry("800x600")
        self.root.configure(bg=BACKGROUNDS["main"])
        self.root.minsize(700, 500)
        self.center_window()
        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
    
    def center_window(self):
        self.root.update_idletasks()
        width = self.root.winfo_width()
        height = self.root.winfo_height()
        x = (self.root.winfo_screenwidth() // 2) - (width // 2)
        y = (self.root.winfo_screenheight() // 2) - (height // 2)
        self.root.geometry(f'{width}x{height}+{x}+{y}')
    
    def load_data(self):
        self.items = load_from_file()
        print(f"✅ 加载了 {len(self.items)} 个角色")
    
    def save_data(self):
        save_to_file(self.items)
    
    def show_screen(self, screen_func, *args):
        if self.current_screen:
            self.current_screen.destroy()
        
        if len(self.screen_history) == 0 or self.screen_history[-1] != screen_func.__name__:
            self.screen_history.append(screen_func.__name__)
        
        self.current_screen = screen_func(self.root, *args)
        self.current_screen.pack(fill="both", expand=True)
    
    def show_launch_screen(self):
        self.show_screen(show_launch_screen, self.items, self.on_enter_app)
    
    def show_selection_screen(self):
        self.show_screen(
            show_selection_screen, 
            self.items, 
            self.on_back,
            self.show_creation_screen,
            self.show_detail_screen,
            self.delete_character
        )
    
    def show_creation_screen(self):
        if not can_add_more_items(self.items):
            messagebox.showwarning("收藏已满", "已达到最大角色数量（4个）！")
            return
        
        self.show_screen(
            show_creation_screen,
            self.items,
            self.on_back,
            self.create_character
        )
    
    def show_detail_screen(self, character):
        self.show_screen(
            show_detail_screen,
            character,
            self.on_back,
            self.delete_character
        )
    
    def on_enter_app(self):
        self.show_selection_screen()
    
    def on_back(self):
        if len(self.screen_history) > 1:
            self.screen_history.pop()
            previous_screen = self.screen_history[-1]
            
            if previous_screen == "show_launch_screen":
                self.show_launch_screen()
            elif previous_screen == "show_selection_screen":
                self.show_selection_screen()
        else:
            self.show_launch_screen()
    
    def create_character(self, name, character_type, level):
        try:
            new_items = create_item(self.items, name, character_type, level)
            
            if new_items != self.items:
                self.items = new_items
                self.save_data()
                messagebox.showinfo("成功", f"角色 {name} 创建成功！")
                self.show_selection_screen()
            else:
                messagebox.showerror("错误", "创建角色失败，请检查输入！")
                
        except Exception as e:
            messagebox.showerror("错误", f"创建角色时出错：{str(e)}")
    
    def delete_character(self, character):
        try:
            new_items = delete_item(self.items, character["id"])
            
            if new_items != self.items:
                self.items = new_items
                self.save_data()
                messagebox.showinfo("成功", f"角色 {character['name']} 已删除")
                
                if len(self.items) == 0:
                    self.show_launch_screen()
                else:
                    self.show_selection_screen()
                    
            else:
                messagebox.showerror("错误", "删除角色失败！")
                
        except Exception as e:
            messagebox.showerror("错误", f"删除角色时出错：{str(e)}")
    
    def on_closing(self):
        if messagebox.askokcancel("退出", "确定要退出程序吗？"):
            self.save_data()
            backup_data(self.items)
            self.root.destroy()